import { useWindowStore } from "@/components/windows/actives/activeWindow.ts";
import { useGlobalConfig } from "@/components/windows/components/config-provider/src/hooks/use-global-config.ts";
import type { AppConfigContext } from "@/components/windows/components/app-config/src/app-config.ts";

export type IApp = {
  key: string;
  name: string;
  icon: string;
  iconType?: string;
  path?: string;
  vm: any;
  click: () => void;
};

const apps: AppConfigContext | undefined = useGlobalConfig().value.apps;
const getShallowComponent = <T extends Component>(comp: () => Promise<T>) => {
  return markRaw(defineAsyncComponent(comp));
};
const getApps = async () => {
  const resultApps = [] as IApp[];
  if (!apps) return resultApps;

  const keys = Object.keys(apps) as (keyof typeof apps)[] as string[];
  const globs = import.meta.glob("../../apps/**/*.vue") as Record<string, () => Promise<Component>>;

  const appPromises = keys.map(async (key) => {
    //获取app配置信息
    const app = apps[key];
    //获取app路径
    const path = Object.keys(globs).find((path) => path.includes(key));
    //获取app组件
    const module = globs[path ?? ""];
    const iconType = app.iconType || "jpg";
    //获取app图标
    const icon = apps[key].icon ?? new URL(`/src/apps/${key}/icon.${iconType}`, import.meta.url).href;
    //默认的打开app函数
    const openAppWindow = () =>
      useWindowStore.createWindow({
        key,
        name: app.name,
        vm: getShallowComponent(module),
        icon,
        path,
        minWidth: app.minWidth,
        minHeight: app.minHeight,
      });

    //获取app点击事件 如果没有则使用默认的打开app函数
    const click = app.click ?? openAppWindow;
    return {
      key,
      name: app.name,
      icon,
      vm: getShallowComponent(module),
      path,
      click,
    };
  });

  // 等待所有异步操作完成
  resultApps.push(...(await Promise.all(appPromises)));

  return resultApps;
};

export default {
  apps,
  getApps,
};
